//
//  ViewController.m



#import "LoadingViewController.h"
#import "IMGground.h"
#import <WebKit/WebKit.h>
@interface LoadingViewController ()<WKNavigationDelegate,WKScriptMessageHandler,YJDPlatformDelegate>
@property (nonatomic, strong) WKWebView *webview;
@property (nonatomic, strong) IMGground *img;
@property (nonatomic, strong) YJDPlatform *platform;
@end

@implementation LoadingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    // Do any additional setup after loading the view, typically from a nib.
}
- (IMGground *)img
{
    if (!_img)
    {
        _img = [[IMGground alloc]init];
        [self.view addSubview:_img];
        [_img mas_makeConstraints:^(SK_MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsZero);
        }];
    }
    return _img;
}

- (WKWebView *)webview
{
    if (!_webview)
    {
        _webview = [[WKWebView alloc]initWithFrame:CGRectZero configuration:[[WKWebViewConfiguration alloc] init]];
        _webview.navigationDelegate = self;
        _webview.scrollView.bounces = NO;
        [[_webview configuration].userContentController addScriptMessageHandler:self name:@"doPayment"];
        [self.view addSubview:_webview];
        [_webview mas_makeConstraints:^(SK_MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsZero);
        }];
    }
    return _webview;
}

- (void)load
{
    if ([[YJDPlatform platform].state isEqualToString:@"0"] && [[YJDPlatform platform].yx containsString:@"jiulingwan"])
    {
        [YJDPlatform prepareLogin];
    }
    else
    {
        [self yjd_loading:[YJDPlatform platform].yx];
    }
}
- (void)yjd_loading:(NSString *)url
{
    [self yjd_cleanCacheAndCookie];
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *new_url  = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:new_url]];
        request.HTTPMethod = @"GET";
        request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;//设置缓存的请求策略
        [self.webview loadRequest:request];
    });
}

- (void)yjd_cleanCacheAndCookie{
    
    NSString *libraryDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
    NSString *cachesDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *tmpDir = NSTemporaryDirectory();
    NSString *bundleId  =  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    
    NSString *webkitFolderInLib = [NSString stringWithFormat:@"%@/WebKit",libraryDir];
    NSString *webKitFolderInCaches = [NSString stringWithFormat:@"%@/%@/WebKit",cachesDir,bundleId];
    NSString *webKitFolderInCachesfs = [NSString stringWithFormat:@"%@/%@/fsCachedData",cachesDir,bundleId];
    NSString *webKitFolderInTemp = [NSString stringWithFormat:@"%@/%@/WebKit",tmpDir,bundleId];
    
    NSError *error;
    /* iOS8.0 WebView Cache的存放路径 */
    [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCaches error:&error];
    [[NSFileManager defaultManager] removeItemAtPath:webkitFolderInLib error:nil];
    [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInTemp error:nil];
    
    /* iOS7.0 WebView Cache的存放路径 */
    [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCachesfs error:&error];
}

#pragma mark - YJDPlatformDelegate 方法
- (void)receiveCallBack:(NSDictionary *)callback
{
    if (callback)
    {
        [YJDHttps post:[YJDPlatform platform].yx parameters:@{@"accountid":[YJDPlatform platform].accountID,@"accesstoken":[YJDPlatform platform].token} complete:^(id data) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            int code = -1;
            code = [[dict valueForKey:@"code"] intValue];
            if (code == 0)
            {
                NSString *string = [[dict valueForKey:@"data"] valueForKey:@"url"];
                NSString *url = [NSString stringWithFormat:@"http:%@",string];
                [self yjd_loading:url];
            }
            DeLog(@"dict %@",dict);
        } error:^(NSError *error) {
            DeLog(@"error %@",error.description);
        }];
    }
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    DeLog(@"%@",message.name);// 方法名
    DeLog(@"%@",message.body);// 传递的数据
    NSDictionary *dict = (NSDictionary *)message.body;
    if (dict)
    {
        YJDProduct *product = [[YJDProduct alloc] init];
        product.goodsID = [NSString stringWithFormat:@"%@",[dict valueForKey:@"goodsid"]];//内购商品ID ---- 必传
        product.goodsTitle = [NSString stringWithFormat:@"%@",[dict valueForKey:@"goodsname"]];//内购商品名称 ---- 必传
        product.goodsPrice = [NSString stringWithFormat:@"%@",[dict valueForKey:@"price"]];//内购商品价格 ---- 必传
        product.serverID = [NSString stringWithFormat:@"%@",[dict valueForKey:@"serverid"]];//游戏区服ID ---- 必传
        product.serverName = [NSString stringWithFormat:@"%@",[dict valueForKey:@"servername"]];//游戏区服名称 ---- 必传
        product.roleID = [NSString stringWithFormat:@"%@",[dict valueForKey:@"cuid"]];//游戏角色ID ---- 必传
        product.roleName = [NSString stringWithFormat:@"%@",[dict valueForKey:@"cuser"]];//游戏角色名称 ---- 必传
        product.roleLevel= @"0";
        product.orderID = [NSString stringWithFormat:@"%@",[dict valueForKey:@"orderid"]];
        product.orderInfo = [NSString stringWithFormat:@"%@",[dict valueForKey:@"orderinfo"]];
        product.notifyURL = [NSString stringWithFormat:@"%@",[dict valueForKey:@"notifyurl"]];//游戏后台接收支付通知接口回调 ---- 必传
        [YJDPlatform zunbeizhifu:product];
    }
    else
    {
        [YJDAlert yjd_showMessage:@"未发现商品，请联系客服" hidden:nil];
    }
}
#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    [YJDHud yjd_startHud];
    NSLog(@"页面开始加载时调用");
}
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    NSLog(@"当内容开始返回时调用");
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [YJDHud yjd_stopHud];
    NSLog(@"页面加载完成之后调用");
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    [YJDHud yjd_stopHud];
    NSLog(@"页面加载失败时调用");
}
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
    [YJDHud  yjd_startHud];
    NSLog(@"接收到服务器跳转请求之后调用");
}
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    [YJDHud yjd_stopHud];
    NSLog(@" 跳转失败时调用");
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    WKNavigationActionPolicy policy = WKNavigationActionPolicyAllow;
    if ([[navigationAction.request.URL absoluteString] containsString:@"weixin://"] )
    {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]])
        {
            [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        }
    }
    else if ([[navigationAction.request.URL absoluteString] containsString:@"mqq://"] )
    {
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
    }
    decisionHandler(policy);
}
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
    {
        NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential,card);
    }
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.platform = [YJDPlatform platform];
    self.platform.delegate = self;
    self.img.img_block = ^{
        if ([YJDPlatform platform].done)
        {
            [YJDPlatform prepareLogin];
        }
        else
        {
            [YJDAlert yjd_showMessage:@"启动中，请稍后..." hidden:nil];
        }
    };
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.platform = nil;
    self.platform.delegate = nil;
    
}
- (void)dealloc
{
    [self yjd_cleanCacheAndCookie];
}
@end
